package com.LeetCode.List;

import org.junit.Test;

/**
 * 判断链表是否有环
 */
public class HasCycle {

    public boolean hasCycle(ListNode head){
        ListNode p1 =head;
        ListNode p2 =head;
        while(p1!=null&&p1.next!=null&&p1.next.next!=null) {
            p1=p1.next.next;
            p2=p2.next;
            if(p1==p2) return true;
        }
        return false;
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node3;
        System.out.println(hasCycle(node1));
    }
}
